package com.xja.house.controller;

import com.xja.house.entity.Users;
import com.xja.house.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("user")
public class UsersController {
    @Autowired
    private UsersService usersService;

    @RequestMapping("login")
    private String userlogin(String name, String password, Model model) {
        try {
            Users userlogin = usersService.userlogin(name);
            if (userlogin == null) {
                model.addAttribute("msg", "用户名不能为空或账号不对");
                return "login";
            }
            if (!userlogin.getPassword().equals(password)) {
                model.addAttribute("msg", "密码不正确");
                return "login";
            }
            model.addAttribute("userlogin", userlogin);
            return "detail";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "error";
    }

    @RequestMapping("check")
    public @ResponseBody
    Map<String, Object> checkname(Model model, String name) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {

            Users user = usersService.userlogin(name);

            if (user != null) {
                map.put("status", "false");
                map.put("msg", "用户名已经存在");
                return map;
            }
            map.put("status", "true");
            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put("status","异常原因");
        return map;
    }
    @RequestMapping("reg")
    public @ResponseBody
    Map<String ,Object> userReg(Model model , Users user){
        Map<String,Object>map=new HashMap<String, Object>();
        try{
            if(user==null){
                map.put("status","false");
                map.put("msg","用户添加失败");
                return map;
            }
            usersService.addUser(user);
            map.put("status","true");
            return map;
        }catch(Exception ex){
            ex.printStackTrace();
        }
        map.put("status","false");
        return  map;
    }
}
